window.onload = function(){
    // console.log(ajax)
    let keywords = document.querySelector('#keywords');
    let send = document.querySelector('#send');
    let tbody = document.querySelector('.table>tbody');
    let prev = document.querySelector('#prev');
    let next = document.querySelector('#next');
    let player = document.querySelector('#player');
    let index = 0;
    function search(){
        let inputValue = keywords.value;
        let url = "https://music.0melon0.cn/search";
        ajax("GET",url,function(data){
            console.log(data.result);
            console.log(data.result.songs);
            let arrSongs = data.result.songs;
            let frag = document.createDocumentFragment();
            arrSongs.forEach(function(item,index){
                let tr = document.createElement('tr');
                tr.innerHTML=`
                <td>${item.name}</td>
                <td>${item.artists[0].name}</td>
                <td>${item.album.name}</td>
                <td>${moment(item.duration).format('mm:ss')}</td>` ;
                tr.setAttribute('data-id',item.id);
                frag.appendChild(tr);
            })
            tbody.innerHTML = "";
            tbody.appendChild(frag);
        },
           {
               "keywords":inputValue,
                "offset":index,
                "limit":10
            })
    }
    send.addEventListener('click',search)
    next.addEventListener('click',function(){
            prev.disabled = false;
            index++;
            search();
    })

    prev.addEventListener('click',function(){
            index--;
            if(index == -1){
                index = 0;
                search();
            }else{
                search();
            }
    })
    tbody.addEventListener('click',function(e){
        let id = +e.target.parentElement.getAttribute('data-id');
        ajax('GET',"https://music.0melon0.cn/song/url",function(data){
            player.src = data.data[0].url;
        },{id:id})
    })
}
